#include <iostream>
#include <vector>
#include <thread>
#include <queue>
#include <condition_variable>
#include <atomic>
#include <functional>

using namespace std;

mutex print_mtx;

class ThreadPool {
private:
    vector<thread> workers;
    queue<function<void()>> tasks;
    mutex mtx;
    condition_variable cv;
    atomic<bool> stop;

    void work_loop() {
        while (true) 
        {
            function<void()> task;
            {
                unique_lock<mutex> lock(mtx);
                cv.wait(lock, [this]() { return stop || !tasks.empty(); });
                if (stop && tasks.empty()) return;
                task = tasks.front();
                tasks.pop();
            }
            task();
        }
    }

public:
    ThreadPool(size_t n) : stop(false) {
        for (size_t i = 0; i < n; i++)
        {
            workers.emplace_back([this]() { work_loop(); });
        }
    }
    
    ~ThreadPool() {
        stop = true;
        cv.notify_all();
        for (auto& t : workers)
            if (t.joinable()) t.join();
    }

    void enqueue(function<void()> task) {
        {
            lock_guard<mutex> lock(mtx);
            tasks.push(task);
        }
        cv.notify_one();
    }
};

int main()
{
    ThreadPool pool(4);
    for(int i = 0; i < 10; ++i) {
      pool.enqueue([i]() {
        { 
            lock_guard<mutex> lock(print_mtx);
            cout << "Task " << i << " running in thread: " << this_thread::get_id() << endl;
        }
            this_thread::sleep_for(chrono::milliseconds(100));
        });
    }
    this_thread::sleep_for(chrono::seconds(1));
    return 0;
}
